layui.use(['table','form','element','tree','util'], function(){
    var table = layui.table;
    var form = layui.form;
    var element = layui.element;
    var layer = layui.layer;
    var $ = layui.$;
    var tree = layui.tree;
    var util = layui.util;

    //加载下拉列表
    $.getJSON(serverUrl + "/sys/grant/get-roles", function (result) {
        $.each(result.data, function (i, item) {
            $("[name=roleList]").append("<option value='"+item.id+"'>"+item.nameZh+"</option>");
        })
        form.render('select');
    });
    //下拉列表change事件
    form.on('select(roleList)', function (data) {
        if(data.value == '') {
            $("#test12").hide();
            return;
        }
        $("#test12").show();
        $.getJSON(serverUrl + "/sys/grant/get-role-resources", {roleId: data.value}, function (result) {
            //基本演示
            tree.render({
                elem: '#test12'
                ,data: result.data
                ,showCheckbox: true  //是否显示复选框
                ,id: 'demoId1'
                ,isJump: true //是否允许点击节点时弹出新窗口跳转
                ,click: function(obj){
                    var data = obj.data;  //获取当前点击的节点数据
                    layer.msg('状态：'+ obj.state + '<br>节点数据：' + JSON.stringify(data));
                }
                // ,accordion: true //手风琴效果
            });
        })
    });
    //按钮事件
    $("#save").click(function () {
        var checkedData = tree.getChecked('demoId1'); //获取选中节点的数据
        var checkedIds = [];
        $.each(checkedData, function (i, parent) {
            checkedIds.push(parent.id);
            if(parent.children) {
                $.each(parent.children, function (j, child) {
                    checkedIds.push(child.id);
                });
            }
        })
        // layer.alert(JSON.stringify(checkedIds), {shade:0});
        var roleId = $("select[name=roleList]").val();
        if(!roleId) {
            layer.msg('请选择角色');
            return;
        }
        $.ajax({
            url: serverUrl + '/sys/grant/update-role-resources',
            data: {roleId: roleId, resourceIds: checkedIds.join(',')},
            type: 'post',
            dataType: 'json',
            success: function (result) {
                layer.msg('success');
            },
            error: function (xhr) {
                layer.msg('error');
            }
        })
    });

});
